package com.ruoyi.web.controller.ssh;

import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.net.service.SSHService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * SSH操作
 */
@Api(tags = "SSH操作")
@RestController
@RequestMapping("/ssh")
public class SSHController extends BaseController {

    @Autowired
    private SSHService sshService;

    @ApiOperation(value = "连接SSH")
    @GetMapping("/connect")
    public AjaxResult connectSSH(String host, int port, String username, String password) {
        try {
            if (sshService.getConnection(host, port) != null) {
                return AjaxResult.success("连接已存在，可以执行命令");
            }

            sshService.createSSHConnection(host, port, username, password);
        }
        catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
        return AjaxResult.success("连接成功");
    }


    @ApiOperation(value = "登录协议栈")
    @GetMapping("/telnet")
    public AjaxResult executeShellCommand(String host, int port, String command) {
        try {
            return AjaxResult.success(sshService.executeShellCommand(host, port, command));
        }
        catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 执行命令
     * @param host
     * @param port
     * @param command
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "执行命令")
    @GetMapping("/execute")
    public AjaxResult executeCommand(String host, int port, String command) {
        try {
            return AjaxResult.success(sshService.executeSSHCommand(host, port, command));
        }
        catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    @ApiOperation(value = "关闭当前SSH连接")
    @GetMapping("/close")
    public AjaxResult closeSSH(String ip, int port) {
        try {
            sshService.closeCurrentConnections(ip, port);
            return AjaxResult.success("关闭当前SSH连接");
        }
        catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    @ApiOperation(value = "关闭SSH连接")
    @GetMapping("/closeAll")
    public AjaxResult closeAllSSH() {
        try {
            sshService.closeAllSSHConnections();
            return AjaxResult.success("关闭所有SSH连接");
        }
        catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }
}
